﻿//*** Guidance generated code ***//
using System;
using System.Collections.Generic;
using System.Linq;

using ProjectBase.Core;

using Survey.Common;
using Survey.Common.Validation;
using Survey.Common.Business.Services;
using Survey.Common.Data;
using Survey.Entity;
using Survey.Entity.Services;

namespace Survey.Business.Services
{
    public class ArticleGroupValidator : EntityValidatorBase<ArticleGroup, int, IArticleGroupDao>
    {
        protected override void Init(RuleCollection<ArticleGroup> rules)
        {
            // string
            rules.For(entity => entity.Name).RequireLengthBetween(0, 250);

            // unique Code
            rules.For(entity => entity.Code).RequireLengthBetween(1, 150)
                .BreakOnError();
            rules.IsUnique(entity => Dao.Find(entity.ID, new CodeListFilter { CodeExact = entity.Code }));

            // Delete
            rules.Assure(IsArticleGroupInUse).WhenDeleting();
        }

        #region Check
        protected virtual ValidationResult IsArticleGroupInUse(ArticleGroup entity, out ValidationMessage message)
        {
            message = null;
            var usedBy = ArticleFacade
                .Find(new ArticleFilter { ArticleGroup = entity, MaxRowsPerPage = 1 })
                .FirstOrDefault();
            if (usedBy.Is())
            {
                message = new ValidationMessage(Str.Messages.ItemIsUsedForEntity3)
                {
                    entity,
                    usedBy,
                    Str.Controllers.ArticleGroup,
                };
                return ValidationResult.Error;
            }
            return ValidationResult.IsValid;
        }
        #endregion Check

        #region IoC
        public IArticleFacade ArticleFacade { protected get; set; }
        #endregion IoC
    }
}